package com.shanshan.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shanshan.system.entity.Branch;
import com.shanshan.system.entity.MeetingClass;
import com.shanshan.system.entity.Period;
import com.shanshan.system.mapper.BranchMapper;
import com.shanshan.system.mapper.MeetingClassMapper;
import com.shanshan.system.mapper.PeriodMapper;
import com.shanshan.system.service.MeetingClassService;
import com.shanshan.system.vo.PeriodContent;
import com.shanshan.system.vo.Result;
import com.shanshan.system.vo.UpdateMeetingClass;
import com.shanshan.system.vo.UpdateUsed;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author keluoyisi
 * @program: shanshan
 * @description:
 * @date 2023-02-09 21:03:25
 */
@Service
@SuppressWarnings("all")
public class MeetingClassServiceImpl  extends ServiceImpl<MeetingClassMapper, MeetingClass> implements MeetingClassService {
    @Autowired
    private MeetingClassMapper meetingClassMapper;

    @Autowired
    private BranchMapper branchMapper;

    @Autowired
    private PeriodMapper periodMapper;

    @Override
    public Result selectMeetingClassAll(int currentPage, int pageSize, PeriodContent periodContent) {
        System.out.println(pageSize);
        System.out.println(currentPage);
        System.out.println(periodContent);
        QueryWrapper<MeetingClass> wrapper = new QueryWrapper<>();
        //默认展示第一期
        if (periodContent.getId()==null){
            wrapper.eq("period_id",1);
        }else {
            wrapper.eq("period_id",periodContent.getId());
        }

        PageHelper.startPage(currentPage,pageSize);
        List<MeetingClass> list = meetingClassMapper.selectList(wrapper);
        int i=1;
        for (MeetingClass meetingClass : list) {
            meetingClass.setUuid(i);
            meetingClass.setNumber1(meetingClass.getNum1()+"/"+meetingClass.getUsed1());
            meetingClass.setNumber2(meetingClass.getNum2()+"/"+meetingClass.getUsed2());
            meetingClass.setNumber3(meetingClass.getNum3()+"/"+meetingClass.getUsed3());
            meetingClass.setNumber4(meetingClass.getNum4()+"/"+meetingClass.getUsed4());
            Branch branch = branchMapper.selectById(meetingClass.getBranchId());
            meetingClass.setBranch(branch.getName());
            Period period1 = periodMapper.selectById(meetingClass.getPeriodId());
            meetingClass.setPeriod(period1.getPeriod());

            //判断是否过期
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDateTime nowTime = LocalDateTime.now();
            LocalDateTime createTime = meetingClass.getCreateTime();
            String endDayStr = nowTime.format(formatter);
            String startDayStr = createTime.format(formatter);


            List<String> timeList = null;
            try {
                timeList = getBetweenDays(startDayStr, endDayStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (timeList.size()>30){
                meetingClass.setState(0);
            }else {
                meetingClass.setState(1);
            }
            i++;

        }

        PageInfo<MeetingClass> info = new PageInfo<>(list);
        return new Result(200,"完成",info);
    }

    @Override
    public Result addContent(UpdateMeetingClass updateMeetingClass) {
        System.out.println(updateMeetingClass);
        Integer integer = meetingClassMapper.updateNum(updateMeetingClass);
        if (integer==1){
            return new Result(200,"添加成功");
        }
        return new Result(500,"添加失败");
    }

    @Override
    public Result updateUsed(UpdateUsed updateUsed) {
        QueryWrapper<Branch> wrapper = new QueryWrapper<>();
        wrapper.eq("name",updateUsed.getBranch());
        Branch branch = branchMapper.selectOne(wrapper);

        QueryWrapper<Period> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("period",updateUsed.getPeriod());
        Period period = periodMapper.selectOne(wrapper1);

        QueryWrapper<MeetingClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("branch_id",branch.getId());
        queryWrapper.eq("period_id",period.getId());

        MeetingClass meetingClass = meetingClassMapper.selectOne(queryWrapper);

        int i=0;
        if (updateUsed.getSort().equals("支部大会")){
            Integer used1 = meetingClass.getUsed1();
            i = meetingClassMapper.updateUsed1(branch.getId(), period.getId(), used1 + 1);
        }
        else if (updateUsed.getSort().equals("支委会议")){
            Integer used1 = meetingClass.getUsed2();
            i = meetingClassMapper.updateUsed2(branch.getId(), period.getId(), used1 + 1);
        }
        else if (updateUsed.getSort().equals("党小组会")){
            Integer used1 = meetingClass.getUsed3();
            i = meetingClassMapper.updateUsed3(branch.getId(), period.getId(), used1 + 1);
        }
        else if (updateUsed.getSort().equals("党课")){
            Integer used1 = meetingClass.getUsed4();
            i = meetingClassMapper.updateUsed4(branch.getId(), period.getId(), used1 + 1);
        }

        if (i==1){
            new Result(200,"成功");
        }

        return new Result(500,"失败");
    }


    /**
     * 获取两个日期中间的所有天数
     *
     * @return
     */
    public static List<String> getBetweenDays(String starttime, String endtime) throws ParseException {
        List<String> betweenTime = new ArrayList<String>();
        try
        {
            Date sdate= new SimpleDateFormat("yyyy-MM-dd").parse(starttime);
            Date edate= new SimpleDateFormat("yyyy-MM-dd").parse(endtime);

            SimpleDateFormat outformat = new SimpleDateFormat("yyyy-MM-dd");

            Calendar sCalendar = Calendar.getInstance();
            sCalendar.setTime(sdate);
            int year = sCalendar.get(Calendar.YEAR);
            int month = sCalendar.get(Calendar.MONTH);
            int day = sCalendar.get(Calendar.DATE);
            sCalendar.set(year, month, day, 0, 0, 0);

            Calendar eCalendar = Calendar.getInstance();
            eCalendar.setTime(edate);
            year = eCalendar.get(Calendar.YEAR);
            month = eCalendar.get(Calendar.MONTH);
            day = eCalendar.get(Calendar.DATE);
            eCalendar.set(year, month, day, 0, 0, 0);

            while (sCalendar.before(eCalendar))
            {
                betweenTime.add(outformat.format(sCalendar.getTime()));
                sCalendar.add(Calendar.DAY_OF_YEAR, 1);
            }
            betweenTime.add(outformat.format(eCalendar.getTime()));
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return betweenTime;
    }


    /**
     * 获取两个日期中间的所有天数xxxxxxxxxxxx
     *
     * @return
     */
    public static List<LocalDateTime> listBetweenDate(String startDayStr, String endDayStr) {
        String[] startArray = startDayStr.split(" ");
        String[] endArray = endDayStr.split(" ");

        String start = startArray[0];
        String startTime = startArray[1];

        String end = endArray[0];
        String endTime = endArray[1];

        if (startTime.equals(endTime)) {
            //如果时间相同，则不用拆开处理了，
            LocalDateTime startDay = LocalDateTime.parse(startDayStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime endDay = LocalDateTime.parse(endDayStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            return listBetweenDate(startDay, endDay);
        } else {
            //"2022-11-04 19:30:00", "2022-11-05 16:30:00"  需要拆开比较，不然只会返回一天，出现BUG
            LocalDateTime startDay = LocalDateTime.parse(start + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime endDay = LocalDateTime.parse(end + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            List<LocalDateTime> dayTimeList = listBetweenDate(startDay, endDay);
            List<LocalDateTime> newDayTimeList = new ArrayList<>();
            for (LocalDateTime item : dayTimeList) {
                LocalDateTime newDayTime = LocalDateTime.of(item.toLocalDate(), LocalTime.parse(startTime));
                newDayTimeList.add(newDayTime);
            }
            newDayTimeList.remove(dayTimeList.size() - 1);

            LocalDateTime lastDayTime = dayTimeList.get(dayTimeList.size() - 1);
            LocalDateTime lastNewDayTime = LocalDateTime.of(lastDayTime.toLocalDate(), LocalTime.parse(endTime));
            newDayTimeList.add(lastNewDayTime);

            return newDayTimeList;
        }
    }

    /**
     * 获取两个日期中间的所有天数
     *
     * @return
     */
    public static List<LocalDateTime> listBetweenDate(LocalDateTime startDay, LocalDateTime endDay) {
        List<LocalDateTime> list = new ArrayList<>();
        long distance = ChronoUnit.DAYS.between(startDay, endDay);
        Stream.iterate(startDay, d -> d.plusDays(1)).limit(distance + 1).forEach(f -> list.add(f));
        return list;
    }
}
